<template>
  <div class="book-betails">
    <div id="statusBar"></div>
    <van-nav-bar title="书籍详情" left-arrow @click-left="returnSearchList" />
    <div class="box" v-if="bookData != null && bookChaptersData.length > 0">
      <div class="top">
      <img :src="bookData.cover" alt="">
      <div>
        <div class="title">{{bookData.title}}</div>
        <div class="author">{{bookData.author}}</div>
        <div class="type">{{bookData.majorCate}} / {{bookData.cat}}</div>
        <div class="other">{{bookData.wordCount}}万字 / {{bookData.totalFollower}}万人在读</div>
        <div class="evaluate-box">
          <div class="fraction">{{score}}</div>
          <div>
            <div class="score"><van-rate v-model="value" :allow-half="true" size="16px" gutter="3px" /></div>
            <div class="score-number">{{tip}}</div>
          </div>
        </div>
      </div>
      </div>
      <div class="short-intro" :class="info ? 'd-text' : ''" @click="info = !info">
        <!-- {{bookData.longIntro}} -->
        <div v-for="(item, index) in bookData.longIntro" :key="index">{{item}}</div>
      </div>
      <div class="catalogue" @click="goToCatalogue(bookData._id)">目录<span>查看目录</span></div>
      <dl class="comment">
        <dt>书籍评论</dt>
        <dd>
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="getShortReviews">
            <div v-for="(item, index) in shortReviewsData" :key="index" class="comment-item">
              <div>
                <div class="top">
                  <img src="../assets/images/user.png" alt="">
                  <div class="author">{{item.author.nickname}}</div>
                  <div class="lv">Lv.{{item.author.lv}}</div>
                  <van-rate v-model="item.rating" :allow-half="true" color="#ffd21e" size="10px" gutter="1px" />
                </div>
                <div class="bottom">
                  <div class="content">{{item.content}}</div>
                  <div>
                    <div class="created">{{item.created | formatDate("yyyy年MM月dd日")}}</div>
                    <div class="likeCount" :class="item.isLike ? 'isLike' : ''" @click="item.isLike = !item.isLike; item.likeCount > 0 ? item.likeCount = 0 : item.likeCount = 1">
                      <van-icon name="good-job-o" size="20" />
                      {{item.likeCount}}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </van-list>
        </dd>
      </dl>
    </div>
    <div class="bottom" v-if="bookData != null && bookChaptersData.length > 0">
      <div><van-button class="addBookshelf" type="primary" block color="#fff" @click="addBook" :class="isRepeat ? 'disable' : ''">{{bookShelf}}</van-button></div>
      <div><van-button type="primary" block color="#00bb86" @click="goToRead(bookData._id)">开始阅读</van-button></div>
    </div>
    <div class="back-top" v-if="btnFlag">
      <van-icon name="back-top" color="#999" size="26" @click="top" />
    </div>
    <!-- <van-overlay :show="showCatalogue" @click="show = false">
      <div class="cataloguePopup">
        <Catalogue />
      </div>
    </van-overlay> -->
  </div>
</template>

<script>
// import Catalogue from '../components/catalogue'
  export default {
    name: 'BookDetails',

    // components: {
    //   Catalogue
    // },

    data() {
      return {
        // 书籍id
        bookId: '',
        // 书籍数据
        bookData: null,
        // 分数
        score: 0,
        // 评分
        value: 0,
        // 评论人数
        tip: 0,
        // 查看全部内容
        info: true,
        // 短评数据
        shortReviewsData: [],
        // 触底加载
        loading: false,
        finished: false,
        // 起始
        start: 0,
        // 结束
        end: 10,
        // 每次十条数据
        number: 10,
        // 显示返回顶部
        btnFlag: false,
        // 收藏
        bookShelf: '加入书架',
        // 是否收藏
        isRepeat: false,
        // 章节目录
        bookChaptersData: []

        // // 目录数据
        // catalogueData: [],
        // // 显示目录
        // showCatalogue: false
      }
    },

    created() {
      // 如果没有bookId返回搜索列表
      if(!this.$route.query.bookId) {
        this.returnSearchList();
      }
      // 获取bookid
      this.bookId = this.$route.query.bookId;
      // 获取书籍数据
      this.getBookData();
      // 获取短评数据
      // this.getShortReviews();
      // 监听页面滚动
      window.addEventListener('scroll', this.scrollToTop);

      // // 获取目录数据(书源=>目录)
      this.getBookSources();
    },

    watch: {
      isRepeat() {
        if(this.isRepeat) {
          this.bookShelf = '已加入书架';
        }else {
          this.bookShelf = '加入书架';
        }
      }
    },

    methods: {
      // 获取书籍数据
      getBookData() {
        this.axios.get(`book-info/${this.bookId}`, {
          // params: {}
        }).then(res => {
          // console.log('res', res);
          if(res.status === 200) {
            // 图片转码
            res.data.cover = decodeURIComponent(res.data.cover.split('/')[2]);
            // 格式化字数
            res.data.wordCount = Math.floor(res.data.wordCount / 10000).toFixed(0);
            // 格式化评论
            res.data.totalFollower = (res.data.totalFollower / 10000).toFixed(1);
            // 格式化长简介
            let long = res.data.longIntro.split('\n');
            let arr = [];
            long.forEach(v => {
              if(v) {
                arr.push(v);
              }
            })
            res.data.longIntro = arr;
            // console.log(arr);
            this.score = res.data.rating.score.toFixed(1);
            this.value = this.score / 2;
            this.tip = res.data.rating.tip;
            this.bookData = res.data;
            // console.log(this.bookData);
            // 检查收藏状态
            this.checkBook();
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 获取短评数据
      getShortReviews() {
        this.axios.get('book/short-reviews', {
          params: {
            book: this.bookId
          }
        }).then(res => {
          // console.log('res', res);
          if(res.status === 200) {
            // 截取数据
            let arr = res.data.docs.slice(this.start, this.end);
            arr.forEach(v => {
              v.isLike = false;
            })
            this.shortReviewsData.push(...arr);
            this.start += this.number;
            this.end += this.number;
            // 加载状态结束
            this.loading = false;
            // 如果数据长度小于十说明已经全部加载完成
            if(arr.length < 10) {
              this.finished = true;
            }
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 监听滚动
      scrollToTop() {
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop >= 400) {
          this.btnFlag = true
        } else {
          this.btnFlag = false
        }
      },

      // 滚回顶部
      top() {
        window.scrollTo(0, 0);
      },

      // 检查是否已经收藏
      checkBook() {
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.bookData._id) {
            this.isRepeat = true;
          }
        })
      },

      // 获取书籍源
      getBookSources() {
        this.axios.get('book-sources', {
          params: {
            view: 'summary',
            book: this.bookId
          }
        }).then(res => {
          // console.log('书籍源res', res);
          if(res.status === 200) {
            // 第一个默认是正版书源
            this.getBookChapters(res.data[0]._id);
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 获取章节
      getBookChapters(_id) {
        this.axios.get(`book-chapters/${_id}`, {
          // params: {}
        }).then(res => {
          // console.log('res', res);
          if(res.status === 200) {
            // 处理link格式
            res.data.chapters.forEach(v => {
              v.link = encodeURIComponent(v.link);
            })
            this.bookChaptersData = res.data.chapters;
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 加入书架
      addBook() {
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          oldBookShelf = [];
        }
        if(this.isRepeat) {
          // 遍历
          oldBookShelf.forEach((item, index) => {
            // 判断是否已经存在
            if(item.bookId === this.bookData._id) {
              // 存在则移除数据
              oldBookShelf.splice(index, 1);
              this.isRepeat = false;
              return;
            }
          })
        }else {
          // 处理数据
          let newBookShelf = {
            // 书名
            title: this.bookData.title,
            // 书id
            bookId: this.bookData._id,
            // 图片
            cover: this.bookData.cover,
            // 第一章地址
            link: this.bookChaptersData[0].link,
            // 章节数
            maxIndex: this.bookChaptersData.length,
            // 当前章节数
            index: 0,
            // 阅读模式为亮
            isLight: true
          }
          // 将新的数据添加进旧数据
          oldBookShelf.push(newBookShelf);
          this.isRepeat = true;
        }
        // 转换成字符串
        oldBookShelf = JSON.stringify(oldBookShelf);
        // 存储到本地存储
        localStorage.setItem('bookShelf', oldBookShelf);
      },

      // 返回搜索列表页
      returnSearchList() {
        // 判断是否搜索模式
        if(this.$route.query.isSearch) {
          this.$router.push({name: 'SearchList'});
        }else {
          this.$router.go(-1);
        }
      },

      // 跳转到目录页（点击查看目录）
      goToCatalogue(bookId) {
        if(this.$route.query.isSearch) {
          this.$router.push({name: 'Catalogue', query: {bookId, isSearch: true}});
        }else {
          this.$router.push({name: 'Catalogue', query: {bookId}});
        }
      },

      // 跳转到阅读页(开始阅读)
      goToRead(bookId) {
        // 判断是否有用户浏览记录
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        let isLoadGame = false;
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.bookData._id) {
            // 存在则调用用户浏览记录访问阅读页
            // 判断是否阅读模式
            if(this.$route.query.isSearch != undefined) {
              // 带入用户浏览记录标记
              // 带入bookid
              // 带入阅读模式标记
              this.$router.push({name: 'Read', query: {link: item.link, bookId, isStorage: true, isSearch: true}});
            }else {
              // 带入bookid
              // 带入用户浏览记录标记
              this.$router.push({name: 'Read', query: {link: item.link, bookId, isStorage: true}});
            }
            isLoadGame = true;
          }
        })
        if(!isLoadGame) {
          // 不存在则默认第一章开始阅读
          // 判断是否阅读模式
          if(this.$route.query.isSearch != undefined) {
            // 带入bookid
            // 带入阅读模式标记
            this.$router.push({name: 'Read', query: {link: this.bookChaptersData[0].link, bookId, isSearch: true}});
          }else {
            // 带入bookid
            this.$router.push({name: 'Read', query: {link: this.bookChaptersData[0].link, bookId}});
          }
        }
      },
    }
  }
</script>

<style lang="less" scoped>
.cataloguePopup {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  z-index: 999999;
}
::v-deep .van-nav-bar {
  position: sticky;
  top: 28px;
}
::v-deep .van-nav-bar .van-icon {
  color: #00bb86;
}
::v-deep .van-nav-bar__title {
  color: #00bb86;
}
::v-deep .van-button--primary.addBookshelf {
  color: #000 !important;
}
.box {
  padding-bottom: 28px;
}
.box>.top {
  display: flex;
  padding: 16px;
  color: #333;
}
.box>.top img {
  margin-right: 20px;
  width: 100px;
  height: 135px;
  border-radius: 2px;
  box-shadow: 2px 2px 4px #aaa;
}
.box>.top .title {
  margin-bottom: 10px;
  color: #000;
  font-size: 16px;
  font-weight: bold;
}
.box>.top .author {
  margin: 5px 0;
}
.box>.top .type {
  color: #999;
}
.box>.top .other {
  margin: 5px 0;
  color: #999;
}
.evaluate-box {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 12px;
}
.evaluate-box .fraction {
  margin-right: 10px;
  font-size: 36px;
  color: #ee0a24;
}
.short-intro {
  position: relative;
  margin-bottom: 10px;
  padding: 0 16px;
  line-height: 1.6;
  font-size: 14px;
  // text-indent:2em;
  box-sizing: border-box;
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    display: block;
    border: 5px solid #999;
    border-top-color: transparent;
    border-right-color: transparent;
    transform: translateX(-120%) translateY(20%) rotate(135deg);
  }
}
.d-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  height: 66px;
  text-overflow: ellipsis;
  overflow: hidden;
  &::after {
    transform: translateX(-120%) translateY(-50%) rotate(-45deg);
  }
}
.catalogue {
  position: relative;
  padding: 16px 16px;
  color: #000;
  font-size: 15px;
  font-weight: bold;
  border-top: 1px solid #e9e9e9;
  border-bottom: 1px solid #e9e9e9;
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    right: 16px;
    display: block;
    width: 8px;
    height: 8px;
    border: 1px solid #999;
    border-top-color: transparent;
    border-right-color: transparent;
    transform: translateY(-50%) rotate(-135deg);
  }
}
.catalogue span {
  padding-left: 10px;
  color: #999;
  font-size: 13px;
  font-weight: normal;
}
.comment {
  padding: 16px;
}
.comment dt {
  color: #000;
  font-size: 15px;
  font-weight: bold;
}
.comment-item {
  padding-top: 15px;
  &>div {
    padding: 12px;
    background-color: #f5f5ff;
    border-radius: 8px;
  }
}
.comment-item .top {
  display: flex;
  align-items: center;
  color: #aaa;
  img {
    padding: 5px;
    width: 15px;
    background-color: #e9e9e9;
    border-radius: 100%;
    opacity: .5;
  }
  .author {
    padding-left: 15px;
  }
  .lv {
    padding: 0 10px;
  }
}
.comment-item .bottom {
  padding-left: 40px;
  color: #aaa;
  .content {
    color: #333;
    padding: 5px 0;
  }
  &>div {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
  }
  .likeCount {
    display: flex;
    align-items: flex-end;
  }
}
// 点赞颜色
.comment-item .bottom.isLike {
  color: #00bb86;
}
// 点赞颜色
.isLike {
  color: #00bb86;
}
.book-betails>.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background-color: #fff;
}
.book-betails>.bottom>div {
  flex: 1;
}
.back-top {
  position: fixed;
  bottom: 80px;
  right: 10px;
}
</style>